package com.wontube.web;

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Locale;

import com.wontube.client.json.JsonWriter;
import com.wontube.web.i18n.I18nManager;
import com.wontube.web.verify.InvalidField;
import com.wontube.web.verify.VerifyResult;

/**
 * @author tanggf(2012-5-9)
 *
 */
public class ServiceResult {
	private boolean isDone;
	private String message;	
	private Object object;
	private VerifyResult verify;
	private String bundleName;
	private Locale locale;	
	
	public ServiceResult(VerifyResult verify, String bundleName){
		this(verify, bundleName, null);
	}
	
	public ServiceResult(VerifyResult verify, String bundleName, Locale locale) {		
		this.verify = verify;
		this.bundleName = bundleName;
		this.locale = locale;
		if(this.verify != null){
			this.setDone(this.verify.isDone());
		}
	}
	
	/**
	 * get i18n message
	 * @return
	 */
	public String getMessage(){
		String key = this.message;
		if(this.verify != null){
			if(this.verify.isDone()){				
				key = this.verify.getMessage();				
			}else{
				List<InvalidField> fields = verify.getInvalidFields();
				return getErrorMessage(fields);
			}
		}		
		
		String value = I18nManager.getMessage(key, bundleName, locale);
		return value == null ? key : value;
	}
	
	public String toJsonString(){
		StringWriter sw = new StringWriter();
		JsonWriter jsonWriter = new JsonWriter(sw);
		try {
			jsonWriter.beginObject();
			jsonWriter.name("isDone").value(isDone);
			jsonWriter.name("message").value(getMessage());			
			jsonWriter.endObject();
			jsonWriter.flush();
			return sw.toString();
		} catch (Exception e) {			
			try {
				jsonWriter.close();
			} catch (IOException es) {
			}
		}	
		return "";
	}
	
	private String getErrorMessage(List<InvalidField> fields) {
		String separator = ", ";
		StringBuilder sb = new StringBuilder();
		for (InvalidField field : fields) {
			String key = field.getMessage();
			String value = I18nManager.getMessage(key, bundleName, locale);
			if(value == null){
				value = key;
			}
			sb.append(value).append(separator);
		}
		return sb.substring(0, sb.length() - separator.length());				
	}

	public boolean isDone() {
		return isDone;
	}
	public void setDone(boolean isDone) {
		this.isDone = isDone;
	}	
	public void setMessage(String message) {
		this.message = message;
	}	
	public Object getObject() {
		return object;
	}
	public void setObject(Object object) {
		this.object = object;
	}	
}
